package net.techwatch.contacts.client;

import java.util.ArrayList;
import java.util.List;

import net.techwatch.contacts.shared.Contact;


import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.RunAsyncCallback;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class ContactsView extends Composite {

	private static final ContactsViewUiBinder uiBinder = GWT.create(ContactsViewUiBinder.class);
	
	interface ContactsViewUiBinder extends UiBinder<Widget, ContactsView> { }
	
	@UiField
	VerticalPanel vPanel;
	
	@UiField
	Button deleteButton;
	
	@UiField
	Button addButton;

	private List<Contact> toDelete = new ArrayList<Contact>();
	private ContactForm form = null;

	private Controller controller;
	
	public ContactsView() {
		initWidget(uiBinder.createAndBindUi(this));

		controller = new Controller(this);
		controller.getAllContacts();
	}

	@UiHandler("deleteButton")
	void onDelete(ClickEvent event) {
		controller.deleteContacts(toDelete);
	}
	
	@UiHandler("addButton")
	void onAdd(ClickEvent event) {
		GWT.runAsync(new RunAsyncCallback() {
		
			@Override
			public void onSuccess() {
				if(form == null) {
					form = new ContactForm(controller);
				}
				
				form.center();
			}
		
			@Override
			public void onFailure(Throwable reason) {
				Window.alert(reason.getMessage());
			}
		});
		
	}

	public void loadData(List<Contact> contacts) {
		vPanel.clear();
		toDelete.clear();
		for (int i = 0; i < contacts.size(); i++) {
			
			final Contact contact = contacts.get(i);
			final CheckBox check = new CheckBox(contact.getFirstName() + " " + contact.getLastName());
			vPanel.add(check);
			check.addClickHandler(new ClickHandler() {

				
				@Override
				public void onClick(ClickEvent event) {
					if (check.getValue()) {
						toDelete.add(contact);
					} else {
						toDelete.remove(contact);
					}
				}
			});
		}
	}
}
